<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\CompanyContract\UpdateContractRequest;
use App\Models\Common\CollOption;
use App\Models\Company\CompanyContract;
use App\Models\Company\CompanyUser;
use App\Models\Company\VipPackage;
use App\Models\Crm\CrmUser;
use Illuminate\Http\Request;
use App\Http\Requests\Admin\CompanyContract\StoreContractRequest;
use Illuminate\Support\Facades\DB;
use Style;

class CompanyContractController extends CommonController{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request){
        $input = arrayFilter($request->only(['keyword', 'category', 'pay']));
        $company_contract = DB::table('company_contract as t1')
            ->join('company_users as t2', 't1.uid', '=', 't2.uid')
            ->select(
                't1.id', 't1.start_time', 't1.end_time', 't1.money', 't1.pay', 't1.pay_time',
                't2.company_name', 't2.uid', 't2.viptime', 't2.vip_resume_number', 't2.vip_integral', 't2.vip_post_number'
            )->where(function($query) use ($input){
                $keyword = (!empty($input['keyword'])) ? $input['keyword'] : '';
                if(strlen($keyword) > 0){
                    $query->where('t2.company_name', 'like', '%' . $keyword . '%');
                }
            })->where(function($query) use ($input){
                $category = (!empty($input['category'])) ? $input['category'] : '';
                if(strlen($category) > 0){
                    $query->where('t1.category', $category);
                }
            })->where(function($query) use ($input){
                $pay = (!empty($input['pay'])) ? $input['pay'] : '';
                if(strlen($pay) > 0){
                    $query->where('t1.pay', $pay);
                }
            })
            ->orderBy('t1.created_at', 'desc')
            ->paginate(20);
        foreach($company_contract as $v){
            $v->start_time = substr($v->start_time, 0, 10);
            $v->end_time = substr($v->end_time, 0, 10);
            $v->viptime = substr($v->viptime, 0, 10);
            $v->pay = CollOption::getOptionName($v->pay, 'pay');
            $v->pay_time = substr($v->pay_time, 0, 10);
        }
        $vip_package = VipPackage::get();
        $pay = CollOption::where('sign', 'pay')->get();
        return Style::view('admin.company_manage.contract.index', compact('company_contract', 'vip_package', 'pay', 'input'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id){

    }

    /**
     * Store a newly created resource in storage.
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreContractRequest $request){
        $admin_user = auth()->guard('admin')->user();
        if($request->responsible_crm_uid == '0'){
            $input = $request->only(['uid', 'category', 'refill_type', 'start_time', 'end_time', 'vip_resume_number', 'vip_integral',
                'vip_post_number', 'resume_number', 'stop_number', 'integral', 'responsible_crm_uid', 'responsible', 'money', 'pay', 'pay_time', 'remark']);
        }else{
            $input = $request->only(['uid', 'category', 'refill_type', 'start_time', 'end_time', 'vip_resume_number', 'vip_integral','stop_number',
                'vip_post_number', 'resume_number','stop_number', 'integral', 'responsible_crm_uid', 'money', 'pay', 'pay_time', 'remark']);
            $input['responsible'] = '';
        }
        $input['admin_uid'] = $admin_user->id;
        //添加合同记录
        $result = CompanyContract::create($input);
        //更新企业用户
        if($result){
            $companyUser = CompanyUser::where('uid', $request->uid)->first(['uid', 'viptime', 'vip_resume_number', 'vip_integral', 'vip_post_number', 'resume_number', 'integral']);
            //正常开通
            if($request->refill_type == '1'){
                $companyUser->vip_resume_number = $request->vip_resume_number;
                $companyUser->vip_integral = $request->vip_integral;
                $companyUser->vip_post_number = $request->vip_post_number;
                $companyUser->viptime = $request->end_time;
            }elseif($request->refill_type == '2'){
                //提前续费
                $companyUser->vip_resume_number = $request->vip_resume_number + $companyUser->vip_resume_number;
                $companyUser->vip_integral = $request->vip_integral + $companyUser->vip_integral;;
                $companyUser->vip_post_number = $request->vip_post_number + $companyUser->vip_post_number;

                //会员时间+当前套餐时间（当不是会员选择了提前续费时，会员时间为套餐的会员）
                //$viptime = date("Y-m-d H:i:s",strtotime($companyUser->viptime) + (int)($request->vip_days)*60*60*24);
                //$end_time = date("Y-m-d H:i:s",time() + (int)($request->vip_days)*60*60*24);
                $companyUser->viptime = $request->end_time;
            }
            //任何情况下非会员的简历数和积分相加
            empty($request->resume_number) ? $requestResumeNumber = 0 : $requestResumeNumber = $request->resume_number;
            empty($request->integral) ? $requestIntegral = 0 : $requestIntegral = $request->integral;
            $companyUser->resume_number = $requestResumeNumber + $companyUser->resume_number;
            $companyUser->integral = $requestIntegral + $companyUser->integral;
            $companyUser->stop_number = $input['stop_number'];
            $companyUser->save();
            return redirect('admin/com_user_reg');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($uid){
        //$admin_user = auth()->guard('admin')->user();
        $company_user = CompanyUser::where('uid', $uid)->first(['viptime']);
        $type = (strtotime($company_user->viptime) >= time()) ? '2' : '1';
        $vip_package = VipPackage::get();
        $pay = CollOption::where('sign', 'pay')->get();
        $crmUser = CrmUser::where('status', 0)->select('uid', 'worker_name')->get();

        return Style::view('admin.company_manage.contract.create', compact('uid', 'type', 'vip_package', 'pay', 'crmUser'));
    }

    /**
     * 选择套餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeVip(Request $request){
        $vip_package = VipPackage::where('id', $request->id)->first();
        if($vip_package){
            $vip_package->start_time = date('Y-m-d H:i:s', time());
            $vip_package->end_time = (!empty($vip_package->vip_days)) ? date("Y-m-d H:i:s", strtotime("+" . $vip_package->vip_days . " days")) : '0000-00-00 00:00:00';
        }
        if($vip_package and $request->refill_type == 2){
            $companyUser = CompanyUser::where('uid', $request->uid)->first(['uid', 'viptime']);
            if(!empty($companyUser->uid)){
                $vip_package->start_time = ($companyUser->viptime > date("Y-m-d H:i:s") ? $companyUser->viptime : date("Y-m-d H:i:s",time()));
                $vip_package->end_time = date("Y-m-d H:i:s", strtotime($companyUser->viptime . "+" . $vip_package->vip_days . " days"));
            }
        }
        return response()->json($vip_package);
    }

    /**
     * Show the form for editing the specified resource.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id){
        $company_contract = CompanyContract::where('id', $id)->first();
        $vip_package = VipPackage::get();
        $pay = CollOption::where('sign', 'pay')->get();
        $crmUser = CrmUser::where('status', 0)->select('uid', 'worker_name')->get();
        return Style::view('admin.company_manage.contract.edit', compact('uid', 'company_contract', 'vip_package', 'pay', 'crmUser'));
    }

    /**
     * Update the specified resource in storage.
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateContractRequest $request, $id){
        $admin_user = auth()->guard('admin')->user();
        if($request->responsible_crm_uid == '0'){
            $input = $request->only(['uid', 'category', 'refill_type', 'start_time', 'end_time', 'vip_resume_number', 'vip_integral',
                'vip_post_number', 'resume_number', 'integral', 'responsible_crm_uid', 'responsible', 'money', 'pay', 'pay_time', 'remark']);
        }else{
            $input = $request->only(['uid', 'category', 'refill_type', 'start_time', 'end_time', 'vip_resume_number', 'vip_integral','stop_number',
                'vip_post_number', 'resume_number', 'integral', 'responsible_crm_uid', 'money', 'pay', 'pay_time', 'remark']);
            $input['responsible'] = '';
        }
        $input['admin_uid'] = $admin_user->id;
        $result = CompanyContract::where('id', $id)->update($input);
        if($result){
            //同步会员信息
            if(!empty($request->c_type) && $request->c_type == '2'){
                $data = [
                    'viptime' => $input['end_time'],
                    'vip_resume_number' => $input['vip_resume_number'],
                    'vip_integral' => $input['vip_integral'],
                    'vip_post_number' => $input['vip_post_number'],
                    'resume_number' => $input['resume_number'],
                    'integral' => $input['integral'],
                    'stop_number' => $input['stop_number'],
                ];
                CompanyUser::where('uid', $input['uid'])->update($data);
                flash('更新会员信息成功', 'success');
            }else{
                flash('更新合同记录成功', 'success');
            }
            return redirect('admin/contract_index');
        }else{
            return back()->with('errors', '更新合同记录失败，请稍后重试！');
        }
    }

    /**
     * Remove the specified resource from storage.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id){
        $result = CompanyContract::where('id', $id)->delete();
        if($result){
            return response()->json(['status' => 0, 'msg' => '合同记录删除成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '合同记录删除失败，请稍后重试！']);
        }
    }

    /**
     * Remove 删除合同关闭会员
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function delContractClose(Request $request){
        $uid = !empty($request->uid) ? $request->uid : '';
        $id = !empty($request->id) ? $request->id : '';
        $result = CompanyContract::where('id', $id)->delete();
        if($result){
            CompanyUser::where('uid', $uid)->update(['viptime' => date('Y-m-d H:i:s', strtotime('-1 days'))]);
            return response()->json(['status' => 0, 'msg' => '删除合同并关闭会员成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '删除合同并关闭会员成功失败，请稍后重试！']);
        }
    }
}
